<?php
/**
 * 洛克斯供应商订单SDK
 * @author hujian
 */
namespace App\Service\VendorClient\ShopluokesiApi;

use App\Service\Code\Normal;
use App\Service\BaseService;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;

class ShopLuokesiApiClient extends BaseService {
    //供应商编号
    const SUPPLIER_CODE = 'shopluokesi';

    private $config = [];

    public function __construct() {
        $this->config = config("api.shopluokesi");
    }

    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder($param = []) {
        $orderInfo   = $param['supplierOrder'];
        $goodsList   = $param['orderGoods'];
        $order       = $param['order'];
        $binfo       = $param['binfo'];
        $companyInfo = $param['companyInfo'];
        $order_sn    = $orderInfo['supplier_dsn'];
        //支付流水号
        $pay_sn = $order['paySerial'] ?? $orderInfo['pay_sn'];
        //订单时间
        $order_time = $orderInfo['cd'] ? date('Y-m-d H:i:s', $orderInfo['cd']) : date('Y-m-d H:i:s', time());
        //支付时间
        $pay_time = isset($order['payTime']) && !empty($order['payTime']) ? date('Y-m-d H:i:s', $order['payTime']) : date('Y-m-d H:i:s', time());
        //运费
        $deliver_money = $orderInfo['deliver_money'] ?? 0.00;
        //下单支付的时候支付信息
        $apply_extends = @json_decode($orderInfo['apply_extends'], true);
        //判断电商平台
        $orderEnterpriseNum = $order['enterpriseNum'] ?? '';
        $enterpriseNum      = isset($apply_extends['enterpriseNum']) && !empty($apply_extends['enterpriseNum']) ? $apply_extends['enterpriseNum'] : $orderEnterpriseNum;
        if (empty($enterpriseNum)) {
            return Normal::returnCode(Normal::FAIL, "电商平台编码不存在");
        }
        $form_id = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_CHANNEL, $enterpriseNum);
        if (empty($form_id)) {
            return Normal::returnCode(Normal::FAIL, "电商平台编码：【{$enterpriseNum}】未映射，请联系管理员处理");
        }
        //判断支付方式是否存在
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $payCommanyCode = $order['payCommanyCode'] ?? $payCommanyCode;
        $payWayInfo     = ServiceConfig::instance()->getConfigByEventsValue(self::SUPPLIER_CODE, ServiceConfig::TYPE_PAY, $payCommanyCode);
        if (empty($payWayInfo)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$payCommanyCode}】未映射，请联系管理员处理");
        }
        //获取下单商品信息
        $palceOrderGoods = [];
        $goodsTotalMoney = 0;
        $way_tax_fee     = 0;
        foreach ($goodsList as $key => $item) {
            $tax_rate = bcadd('1', (string)$item['tax_rate'], 4);
            $price    = $item['price'];
            $spec_num = $item['spec_num'];
            $quantity = $item['quantity'];
            //单个商品的含税单价
            $singlePrice = bcdiv((string)$price, (string)$spec_num, 3);
            //单个商品的不含税单价
            $goodsPrice      = bcdiv((string)$price, (string)$tax_rate, 3);
            $goodsPrice      = bcdiv((string)$goodsPrice, (string)$spec_num, 3);
            $goodsPrice      = bcmul((string)$goodsPrice, (string)100, 1);
            $goodsPrice      = bcdiv((string)ceil($goodsPrice), 100, 2);
            $buyNum          = $spec_num * $quantity;
            $goodsTotalPrice = bcmul((string)$goodsPrice, (string)$buyNum, 2);
            //商品关税当前币种最小单位（分）
            $goodsCustomsTax = bcsub((string)$singlePrice, (string)$goodsPrice, 2);
            $taxAll          = bcmul((string)$goodsCustomsTax, (string)$buyNum, 2);
            //下单商品组
            $goodsInfo         = [
                'hg_code'    => $item['supplier_skucode'],//商品编码
                'goods_name' => $item['goods_name'],//商品名称
                'qty'        => (int)$buyNum,//订购数量
                'unit'       => $item['spec_name'],//单位（如件、只、箱等）
                'price'      => $goodsPrice,//购买价格(元)
            ];
            $palceOrderGoods[] = $goodsInfo;
            $goodsTotalMoney   = bcadd((string)$goodsTotalMoney, (string)$goodsTotalPrice, 2);
            $way_tax_fee       = bcadd((string)$way_tax_fee, (string)$taxAll, 2);
        }
        //订单总价（商品总额 + 税费 + 运费）
        $totalMoney = bcadd((string)$goodsTotalMoney, (string)$deliver_money, 2);
        $totalMoney = bcadd((string)$totalMoney, (string)$way_tax_fee, 2);
        //用户实际支付金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单优惠金额
        $discount_money = bcsub((string)$totalMoney, (string)$real_total_money, 2);
        //推送数据
        $requestParam = [
            'from_id'        => $form_id,//订单来源网站id
            'order_no'       => $order_sn,//订单编号
            'payamount'      => $real_total_money,//实付金额（商品总额+税费+运费-优惠总金额）（元）
            'postfee'        => $deliver_money,//运费（元）
            'buyer_account'  => $orderInfo['buyer_phone'],//买家账号
            'real_name'      => $orderInfo['buyer_realname'],//购买人真实姓名
            'people_id'      => $orderInfo['buyer_idcard'],//购买人身份证号
            'order_time'     => $order_time,//交易时间(2020-1-2 11:20:30)
            'tax_amount'     => $way_tax_fee,//税（元）
            'dis_amount'     => $discount_money,//优惠总金额（默认为0）（元）
            'payment_no'     => $order['paySerial'] ?? $apply_extends['paySerial'],//支付单号（交易流水号,必须真实对应,海关审查）
            'pay_type'       => (string)$payWayInfo,//支付类型编号（查看：附2）
            'logistics_name' => '中通国际',//快递名称（查看：附3）
            'consignee'      => $orderInfo['receive_name'],//收货人
            'province'       => $orderInfo['province'],//省份
            'city'           => $orderInfo['city'],//城市
            'district'       => $orderInfo['district'],//地区
            'addr'           => $orderInfo['receive_address'],//收货人详细地址
            'consignee_tel'  => $orderInfo['recveive_phone'],//收货人手机号
            'pay_time'       => $pay_time,//支付时间
            'goods'          => $palceOrderGoods,//商品明细
        ];
        // echo json_encode($requestParam, 320);die;
        $data = [
            'method' => 'createOrder',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }

    /**
     * 取消订单
     * @param $data
     * @return array|string
     */
    public function cancelOrder($params = []) {
        $requestParam = [
            'order_no' => $params['supplierOrder']['supplier_dsn'],
        ];
        $data         = [
            'method' => 'cancelOrder',
            'data'   => $requestParam,
        ];
        $res          = $this->execute($data);
        if ($res['code'] == Normal::SUC) {
            return Normal::returnCode(Normal::SUC, $res['data']['msg']);
        }
        return $res;
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function sign($data) {
        ksort($data);
        $strA = '';
        foreach ($data as $k => $v) {
            $strA .= "{$k}{$v}";
        }
        $strB = $this->config['APP_SECRET'] . $strA . $this->config['APP_SECRET'];
        $strC = md5($strB);
        return strtoupper($strC);
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute($param = []) {
        if (!isset($this->config['ACTION'][$param['method']])) {
            return Normal::returnCode(Normal::FAIL, "请求路由未设置");
        }
        if (empty($param['data'])) {
            return Normal::returnCode(Normal::FAIL, "数据不能为空");
        }
        $url = $this->config['API_DOMAIN'] . $this->config['ACTION'][$param['method']];
        if (empty($url)) {
            return Normal::returnCode(Normal::FAIL, "接口地址不能为空");
        }
        $pushData         = [
            'app_key'     => $this->config['APP_KEY'],
            'return_type' => 'json',
            'timestamp'   => time(),
            'data'        => json_encode($param['data']),
        ];
        $pushData['sign'] = $this->sign($pushData);
        $parameter        = [
            [
                'tag'    => self::SUPPLIER_CODE . '_' . $param['method'],
                'uid'    => IdService::instance()->getOtherID(),
                'url'    => $url,
                'data'   => $pushData,
                'method' => 'post',
                'format' => 'form-data',
                'header' => [],
            ],
        ];
        $resTask          = TaskWorker::instance()->addTask($parameter);
        $resTask          = current($resTask);
        $result           = @json_decode($resTask['response']['result'], true);
        if (isset($result['code']) && $result['code'] == 10000) {
            return Normal::returnCode(Normal::SUC, "操作成功", $result);
        } else {
            $msg = $result['msg'] ?? '请求失败';
            return Normal::returnCode(Normal::FAIL, $msg);
        }
    }

    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $params = [] )
    {
        $requestParam = [
            'order_no' => $params['supplier_dsn']
        ];
        $data         = [
            'method' => 'orderExpress',
            'data'   => $requestParam,
        ];
        return $this->execute($data);
    }
}
